<?php
/**
 * Controller pre admin-hosting
 * @author Tomas Srna
 * @package bakalarka
 */

class AdminHostingController extends Controller
{
	protected $resource = 'admin-hosting';
	
	/**
	 * Index
	 */
	public function index()
	{
		$t = Template::instance();
		
		$dv = new DynamicView();
		$dv->buttonAdd = true;
		$dv->primaryKeys = array('id');
		$dv->baseUrl = APPBASE."admin/hosting";
		
		$dv->itemCount = Selector::select("count(*) as c")->from('hosting')
			->fetch()->current()->c;
			
		$t->dv = $dv;
		$t->dvw = new DynamicViewWriter($t->dv, $t);
		
		$t->title = L::selected()->hostingAdmin;
		$t->text = "";
		
		$t->render('dynamic-view');
	}
	
	/**
	 * Data
	 */
	public function data()
	{
		$params = $_GET;
		
		$t = Template::instance();
		
		// Kontrola vstupov
		$by_possible = array("id", "name", "space", "dbcount", "servername",
						"adminmail", "php", "ssl", "active");
		
		$dt = new DynamicTable();
		$dt->primaryKeys = array('id');
		$dt->itemCount = Selector::select("count(*) as c")->from('hosting')
			->fetch()->current()->c;
		
		if(!$dt->check($params, $by_possible))
			$t->error = L::selected()->invalidInput;
			
		if(!property_exists($t, 'error'))
		{
			$dt->headers['id'] = L::selected()->id;
			$dt->headers['name'] = L::selected()->name;
			$dt->headers['space'] = L::selected()->space;
			$dt->headers['dbcount'] = L::selected()->dbcount;
			$dt->headers['servername'] = L::selected()->servername;
			$dt->headers['adminmail'] = L::selected()->adminmail;
			$dt->headers['php'] = L::selected()->php;
			$dt->headers['ssl'] = L::selected()->ssl;
			$dt->headers['active'] = L::selected()->active;
			
			$dt->writers['active'] = new YesNoWriter();
			$dt->writers['php'] = new EnabledDisabledWriter();
			$dt->writers['ssl'] = new EnabledDisabledWriter();
			$dt->writers['space'] = new SpaceWriter();
			
			if(!array_key_exists('page', $params))
				$params['page'] = 1;
			
			$select = Selector::select()
						->from(HostingModel::struct())
						->page($params['page'])
						->by($params);
			
			$dt->data = $select->fetch();
			
			$t->dtw = new DynamicTableWriter($dt, $t);
		}
			
		$t->dt = $dt;
		$t->render('dynamic-table');
	}
	
	/**
	 * Edit
	 * @param bool $create		Vytvarame noveho uzivatela?
	 */
	public function edit($create = false)
	{
		$t = Template::instance();
		
		if($create)
		{
			$t->title = L::selected()->createHosting;
			
			$_POST['updated'] = new Expression('NOW()');
			$_POST['used'] = 0;
			
			if(getenv('REQUEST_METHOD') == 'POST')
				$model = HostingModel::create($_POST);
			else
				$model = NULL;
		}
		else
		{
			$t->title = L::selected()->editHosting;
			
			// Skontrolujeme ci existuje objekt a nacitame ho
			if(	!array_key_exists('id', $_GET))
				throw new Exception('L::errorObjectNotFound;'.
						json_encode(array('HostingModel(?)')));
						
			$model = HostingModel::load(array(
						'id' => $_GET['id']
					));
					
			if(!$model)
				throw new Exception('L::errorObjectNotFound;'.
					json_encode(array(sprintf('HostingModel(%s)',
					$_GET['id']))));
		}
		
		if(getenv('REQUEST_METHOD') == 'POST')
		{
			$f = new HostingForm($t, $_POST);
			
			if($f->validate())
			{
				// Kontrola duplicity
				if($create)
				{
					$c = Selector::select('count(*) as c')
							->from(HostingModel::struct())
							->where('`name` = ? OR `servername` = ? OR `root` = ?', 
								$_POST['name'], $_POST['servername'], $_POST['root'])
							->fetch()->current()->c;

					if($c > 0)
						$dup = true;
					else
						$dup = NULL;
				}
				
				if(!$create || $dup == NULL)
				{
					$model->set($_POST);
					
					$model->updated = new Expression('NOW()');
					
					$model->save();
					if($create)
						Logger::log('L::objectCreated_s;'.
							json_encode((string)$model), 'info');
					else
						Logger::log('L::objectChanged_s;'.
							json_encode((string)$model), 'info');
					$this->autoredir();
				}
				else
					$t->error = L::selected()->duplicity;
			}
			else
				$t->error = L::selected()->invalidForm;
		}
		else
		{
			$f = new HostingForm($t, $model);
		}
		
		$fw = new FormWriter($f);
		$t->fw = $fw;
		
		$t->render('form');
	}

	/**
	 * Vytvorenie noveho hostingu
	 */
	public function create()
	{
		// Zavolame edit s $create = true
		return $this->edit(true);
	}
	
	/**
	 * Odstranenie riadka
	 */
	public function delete()
	{
		// Skontrolujeme ci existuje objekt a nacitame ho
		if(	!array_key_exists('id', $_GET))
			throw new Exception('L::errorObjectNotFound;'.
					json_encode(array('HostingModel(?)')));
					
		$model = HostingModel::load(array(
			'id' => $_GET['id'],
		));
		
		if(!$model)
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array(sprintf('HostingModel(%s)', $_GET['id']))));
				
		// Zmazeme vsetky zavislosti
		Selector::select()->from(AclModel::struct())->where('resource = ?',
			'hosting:'.$model->name)->delete();
		Selector::select()->from(HostingFtpModel::struct())
			->where('hosting_id = ?', $model->id)->delete();
		
		$dbq = Selector::select()->from(HostingMysqlModel::struct())
				->where('hosting_id = ?');
		$dbs = $dbq->fetch();
		foreach ($dbs as $db)
		{
			Db::instance()->query(
				sprintf('call mysql_delete(%s)',
					Db::instance()->quote($db->name))
			);
		}
		$dbq->delete();
		
		// Zmazeme samotny riadok
		$model->delete();
		
		// Zalogujeme
		Logger::log('L::objectDeleted_s;'.
			json_encode((string)$model), 'info');
		
		$this->autoredir();
	}
}
